<template>
  <!-- 演练评价-->
  <div class="emerDrill">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.drill_delete" @click="handleDelete">删 除</el-button>
          <el-button type="warning" size="small" icon="el-icon-download" plain v-if="permission.drill_export" @click="handleExport">导出</el-button>
        </template>

        <!-- 评价状态 -->
        <template slot="pjzt" slot-scope="scope">
          <div v-if="scope.row['pjzt']=='1'">
            <el-form label-width="0px">
              <el-button type="success" size="small" round >评价中</el-button>
            </el-form>
          </div>
          <div v-else>
            <el-button type="primary" size="small" round >已评价</el-button>
          </div>
        </template>

        <!-- 相关附件表格自定义 -->
        <template slot="xgfj" slot-scope="scope">
          <div v-if="scope.row['xgfj']!=''" class="enclosure_div">
            <a :href="downloadHead + scope.row['xgfj']">
              <i class="el-icon-download"></i>下载附件
            </a>
          </div>
          <span v-else>-</span>
        </template>

        <!-- 相关附件表单自定义 -->
        <template slot="xgfjForm">
          <div>
            <el-upload action="/api/fileManager/upload/file" :headers="SetHeaders" :file-list="xgfjFileList" :before-upload="beforeUploadXGFJ" :on-remove="handleRemoveXGFJ" :on-success="uploadXGFJSuccess">
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
          </div>
        </template>

        <!-- 其它参演部门表格自定义 -->
        <template slot="qtcybm" slot-scope="scope">
          <div>{{qtcybm(scope.row)}}</div>
        </template>

        <!-- 演练实施人员表格自定义 -->
        <template slot="ylssry" slot-scope="scope">
          <div>{{ylssry(scope.row)}}</div>
        </template>

        <!-- 主要参演人员表格自定义 -->
        <template slot="zycyry" slot-scope="scope">
          <div>{{zycyry(scope.row)}}</div>
        </template>

      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove, getUserInfoList} from "@/api/emer/drill";
  import {getDeptList} from "@/api/mmhi/major_dangerous_sources";
  import {getSybmList} from "@/api/emer/plan";
  import {getToken} from "@/util/auth";
  import {mapGetters} from "vuex";

  const tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          refreshBtn: true,
          columnBtn: true,
          calcHeight: 30,
          dialogWidth: 950,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          addBtn: false,
          editBtnText: "评价",
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "演练名称",
              prop: "ylmc",
              align: "center",
              readonly:true,
              search: true
            },
            {
              label: "实际演练日期",
              prop: "sjylrq",
              align: "center",
              width: "100px",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "实际演练日期",
                trigger: "click"
              }]
            },
            {
              label: "演练实施人员",
              prop: "ylssry",
              align: "center",
              width: "100px",
              multiple: true,
              type: "tree",
              dicUrl: "/api/emerDrill/drill/getPersonInfo",
              props: {
                label: "name",
                value: "id",
              },
              checkStrictly: true,
              slot:true,
              rules: [{
                required: true,
                message: "请选择演练实施人员",
                trigger: "click"
              }]
            },
            {
              label: "主要参演人员",
              prop: "zycyry",
              align: "center",
              width: "100px",
              multiple: true,
              type: "tree",
              dicUrl: "/api/emerDrill/drill/getPersonInfo",
              props: {
                label: "name",
                value: "id",
              },
              checkStrictly: true,
              slot:true,
              rules: [{
                required: true,
                message: "请选择主要参演人员",
                trigger: "click"
              }]
            },
            {
              label: "其它参演部门",
              prop: "qtcybm",
              align: "center",
              width: "100px",
              type:"tree",
              multiple: true,
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              slot:true,
              rules: [{
                required: true,
                message: "请选择其它参演部门",
                trigger: "click"
              }]
            },
            {
              label: "演练内容",
              prop: "ylnr",
              align: "center",
              type: "textarea",
              maxlength: 1000,
              span: 24,
              minRows: 6,
              hide: true,
              rules: [{
                required: true,
                message: "请输入演练内容",
                trigger: "blur"
              }]
            },
            {
              label: "演练目的",
              prop: "ylmd",
              align: "center",
              maxlength: 250,
              span: 24,
              rules: [{
                required: true,
                message: "请输入演练目的",
                trigger: "blur"
              }]
            },
            {
              label: "演练过程",
              prop: "ylgc",
              align: "center",
              maxlength: 250,
              span: 24,
              rules: [{
                required: true,
                message: "请输入演练过程",
                trigger: "blur"
              }]
            },
            {
              label: "演练小结",
              prop: "ylxj",
              align: "center",
              maxlength: 250,
              span: 24,
              rules: [{
                required: true,
                message: "请输入演练小结",
                trigger: "blur"
              }]
            },
            {
              label: "不足因素描述",
              prop: "bzysms",
              align: "center",
              maxlength: 250,
              width: "100px",
              span: 24,
              rules: [{
                required: true,
                message: "请输入不足因素描述",
                trigger: "blur"
              }]
            },
            {
              label: "是否整改",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_drill_sfzg",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              prop: "sfzg",
              align: "center",
              dataType: "number",
              rules: [{
                required: true,
                message: "请选择是否整改",
                trigger: "blur"
              }]
            },
            {
              label: "评价意见",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_drill_pjyj",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              prop: "pjyj",
              align: "center",
              rules: [{
                required: true,
                message: "请选择评价意见",
                trigger: "blur"
              }]
            },
            {
              label: "评价状态",
              prop: "pjzt",
              align: "center",
              slot: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "相关附件",
              prop: "xgfj",
              align: "center",
              span: 24,
              slot: true,
              formslot: true,
              viewDisplay: false,
              rules: [
                {
                  required: true,
                  message: "请选择相关附件",
                  trigger: "blur"
                }
              ]
            },
            {
              label: "企业id",
              prop: "bladeDeptId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "租户id",
              prop: "tenantId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建人",
              prop: "createUser",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建部门",
              prop: "createDept",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建时间",
              prop: "createTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "演练计划id",
              prop: "emerDrillPlanId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
          ]
        },
        data: [],

        //其它参演部门
        qtcybmList: {},
        //演练实施人员
        ylssryList: {},
        //主要参演人员
        zycyryList: {},
        // 附件
        xgfjFileList: [],
        downloadHead: "/api/fileManager/download/",
        SetHeaders: { "Blade-Auth": getToken() },
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.drill_add, false),
          viewBtn: this.vaildData(this.permission.drill_view, false),
          delBtn: this.vaildData(this.permission.drill_delete, false),
          editBtn: this.vaildData(this.permission.drill_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      this.initData();
    },
    methods: {
      // 初始化数据
      initData() {
        getDeptList(tenantId).then(res => {
          const column = this.findObject(this.option.column, "qtcybm");
          column.dicData = res.data.data;
        }).then(() => {
          this.getQtcybm();
        }).then(() => {
          this.getYlssry();
        }).then(() => {
          this.getZycyry();
        });
      },

      // 获取其它参演部门列表
      getQtcybm() {
        getSybmList().then(res => {
          this.qtcybmList = {};
          res.data.data.forEach(item => {
            this.qtcybmList[item.id] = item.deptName;
          });
        })
      },
      // 显示其它参演部门列
      qtcybm(row) {
        if(row.qtcybm === undefined || typeof row.qtcybm === "object") {
          return "";
        }
        const arr = row.qtcybm.split("|");
        const faults = [];
        for(let i = 0 ; i < arr.length ; i++) {
          const fault = this.qtcybmList[arr[i]] === undefined ? arr[i] : this.qtcybmList[arr[i]];
          faults.push(fault);
        }
        return faults.join("|");
      },

      // 获取演练实施人员列表
      getYlssry() {
        getUserInfoList().then(res => {
          this.ylssryList = {};
          res.data.data.forEach(item => {
            this.ylssryList[item.id] = item.name;
          });
        })
      },
      // 显示演练实施人员列
      ylssry(row) {
        if(row.ylssry === undefined || typeof row.ylssry === "object") {
          return "";
        }
        const arr = row.ylssry.split("|");
        const faults = [];
        for(let i = 0 ; i < arr.length ; i++) {
          const fault = this.ylssryList[arr[i]] === undefined ? arr[i] : this.ylssryList[arr[i]];
          faults.push(fault);
        }
        return faults.join("|");
      },

      // 获取主要参演人员列表
      getZycyry() {
        getUserInfoList().then(res => {
          this.zycyryList = {};
          res.data.data.forEach(item => {
            this.zycyryList[item.id] = item.name;
          });
        })
      },
      // 显示主要参演人员列
      zycyry(row) {
        if(row.zycyry === undefined || typeof row.zycyry === "object") {
          return "";
        }
        const arr = row.zycyry.split("|");
        const faults = [];
        for(let i = 0 ; i < arr.length ; i++) {
          const fault = this.zycyryList[arr[i]] === undefined ? arr[i] : this.zycyryList[arr[i]];
          faults.push(fault);
        }
        return faults.join("|");
      },

      rowSave(row, done, loading) {
        row.qtcybm = typeof row.qtcybm === "object" ? row.qtcybm.join("|") : row.qtcybm;
        row.ylssry = typeof row.ylssry === "object" ? row.ylssry.join("|") : row.ylssry;
        row.zycyry = typeof row.zycyry === "object" ? row.zycyry.join("|") : row.yalx;
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        const arr =  row.qtcybm = typeof row.qtcybm === "object" ? row.qtcybm.join("|") : row.qtcybm.split(",");
        const arrS = row.ylssry = typeof row.ylssry === "object" ? row.ylssry.join("|") : row.ylssry.split(",");
        const arrT = row.zycyry = typeof row.zycyry === "object" ? row.zycyry.join("|") : row.zycyry.split(",");
        const faults = [];
        const faultAs = [];
        const faultTs = [];
        if(arr instanceof Array){
          for(let i = 0 ; i < arr.length ; i++) {
            const fault = arr[i];
            faults.push(fault);
          }
          row.qtcybm = faults.join("|");
        }
        if(arrS instanceof Array) {
          for (let i = 0; i < arrS.length; i++) {
            const faultA = arrS[i];
            faultAs.push(faultA);
          }
          row.ylssry = faultAs.join("|");
        }
        if(arrS instanceof Array) {
          for(let i = 0 ; i < arrT.length ; i++) {
            const faultT = arrT[i];
            faultTs.push(faultT);
          }
          row.zycyry = faultAs.join("|");
        }
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (type === "edit") {
          if (this.form.pjzt === "2") {
            this.$message.warning("当前应急演练已不可评价!");
            return;
          }
        }
        this.xgfjFileList = [];
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            const arrS = res.data.data.qtcybm.split("|");
            const arrT =  res.data.data.ylssry.split("|");
            const arr =  res.data.data.zycyry.split("|");
            const faultAs = [];
            const faultTs = [];
            const faults = [];
            for(let i = 0 ; i < arrS.length ; i++) {
              const faultA = arrS[i];
              faultAs.push(faultA);
            }
            for(let i = 0 ; i < arrT.length ; i++) {
              const faultT = arrT[i];
              faultTs.push(faultT);
            }
            for(let i = 0 ; i < arr.length ; i++) {
              const fault = arr[i];
              faults.push(fault);
            }
            res.data.data.qtcybm = faultAs.join(",");
            res.data.data.ylssry = faults.join(",");
            res.data.data.zycyry = faults.join(",");
            this.form = res.data.data;
            if (type === "edit") {
              if(JSON.stringify(this.form.bladeFile)!='{}'){
                this.xgfjFileList.push({
                  name: this.form.bladeFile.fileName,
                  response: {
                    code: 200,
                    success: true,
                    msg: "操作成功",
                    data: this.form.bladeFile
                  }
                });
              }
            }
          });
        }
        done();
      },

      /**
       * 上传附件
       */
      // 上传附件前
      beforeUploadXGFJ() {
        const isLimit = this.xgfjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
        }
        return isLimit;
      },

      // 上传附件成功
      uploadXGFJSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.xgfjFileList = fileList;
        this.form.xgfj = response.data.id;
      },

      // 删除附件
      handleRemoveXGFJ(file, fileList) {
        this.xgfjFileList = fileList;
        this.form.xgfj = "";
      },

      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      handleExport() {
        this.$confirm("是否导出演练评价信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/emerDrill/drill/export-drill?${this.website.tokenHeader}=${getToken()}`);
        });
      }
    }
  };
</script>

<style lang="scss">
  .hazardManager {
    .el-form-item__label {
      width: 100px !important;
    }
    .avue-form__row {
      .el-form-item__content {
        margin-left: 100px !important;
      }
    }
  }

</style>

<style lang="scss" scpoed>
  .emerDrill {
    .avue-crud {
      .avue-crud__search {
        .avue-form__row:nth-child(1) {
          .el-form-item__label {
            text-align: unset;
            width: 90px !important;
          }

          .el-form-item__content {
            margin-left: 90px !important;
          }
        }
      }
    }

    .enclosure_div {
      a {
        font-size: 12px;
        color: #409eff;

        i {
          margin-right: 5px;
        }
      }
    }
  }

  .avue-dialog {
    .el-dialog {
      .avue-group {
        .avue-form__group {
          .el-form-item {
            .el-form-item__label {
              width: 110px !important;
            }

            .el-form-item__content {
              margin-left: 110px !important;
            }
          }
        }
      }
    }
  }

</style>
